﻿//---------------------------------------------------------------------
// Author: Harley Green
//
// Description: Class to place MSMQ Messages onto a queue
//
// Creation Date: 2008/3/8
//---------------------------------------------------------------------


using System.Management.Automation;
using System.Messaging;

namespace Pscx.Commands.Messaging
{
    [Cmdlet(VerbsCommunications.Send, PscxNouns.MSMQMessage,
        DefaultParameterSetName = "Named", SupportsShouldProcess = true)]
    public class SendMSMQMessage : MessageQueueCmdlet
    {
        private object inputObject;

        [Parameter(Position = 0, Mandatory = true)]
        public object InputObject
        {
            get { return inputObject; }
            set { inputObject = value; }
        }

        [Parameter]
        public SwitchParameter Recoverable { get; set; }

        protected override void ProcessRecord()
        {
            if (!ShouldProcess(GetPath())) return;
            if (!Exists) return;
            using (MessageQueue queue = GetQueue())
            {
                using (Message message = new Message(inputObject))
                {
                    if (Recoverable.IsPresent)
                    {
                        message.Recoverable = true;
                    }
                    if (queue.Transactional)
                    {
                        queue.Send(message, new MessageQueueTransaction());
                    }
                    else
                    {
                        queue.Send(message);
                    }
                }
            }
        }
    }
}